import psutil
import json
from app.machines.mac import MacInfo

class NetworkInof:

    def get_network_info():
        network_dict = {}
        # 网络I/O统计信息
        network_ios = psutil.net_io_counters()
        # print(network_ios)
        # 发送字节 kbps
        bytes_sent = round(network_ios.bytes_sent/1024,2)
        # 接收字节 kbps
        bytes_recv = round(network_ios.bytes_recv/1024,2)
        # 发送数据包数
        packets_sent = network_ios.packets_sent
        # 接收数据包数
        packets_recv = network_ios.packets_recv
        # 接收错误数据包数
        errin = network_ios.errin
        # 发送错误数据包数
        errout = network_ios.errout
        # 丢弃接收数据包数
        dropin = network_ios.dropin
        # 丢弃发送数据包数
        dropout = network_ios.dropout

        # print("----------------------------")
        # pernic=True，则对于系统上安装的每个网络接口，将以字典的形式返回相同的信息
        network_ios_detail = psutil.net_io_counters(pernic=True)
        # print(network_ios_detail)
        # net_detail = json.loads(network_ios_detail)
        net_list = []
        for key in network_ios_detail.keys():
            net_detail = network_ios_detail[key]
            if net_detail[0] > 0 and net_detail[1] > 0 :
                net_dict = {}
                net_dict['mac_code'] = MacInfo.get_mac()
                net_dict['network_name'] = key
                net_dict['bytes_sent'] = round(net_detail[0]/1024,2)
                net_dict['bytes_recv'] = round(net_detail[1]/1024,2)
                net_dict['packets_sent'] = net_detail[2]
                net_dict['packets_recv'] = net_detail[3]
                net_dict['errin'] = net_detail[4]
                net_dict['errout'] = net_detail[5]
                net_dict['dropin'] = net_detail[6]
                net_dict['dropout'] = net_detail[7]
                net_list.append(net_dict)
        # print("==================================")
        # 网络连接
        # network_connections = psutil.net_connections(kind='inet')
        # print(network_connections)
        # print("----------------------------")
        # 网络地址
        # network_addresses = psutil.net_if_addrs()
        # print(network_addresses)
        # print("----------------------------")
        # 网络状态
        # network_stats = psutil.net_if_stats()
        # print(network_stats)
        network_dict['bytes_sent'] = bytes_sent
        network_dict['bytes_recv'] = bytes_recv
        network_dict['packets_sent'] = packets_sent
        network_dict['packets_recv'] = packets_recv
        network_dict['errin'] = errin
        network_dict['errout'] = errout
        network_dict['dropin'] = dropin
        network_dict['dropout'] = dropout

        # print(net_list)
        # for n in net_list:
        #     print(n)
        return net_list

if __name__ == '__main__':
    network = NetworkInof()
    net = network.get_network_info()
    network_json = json.dumps(net)
    print(network_json)